package com.hassean.we.admin.common.Interceptor;

import com.hassean.we.admin.service.RedisService;
import com.xiaoleilu.hutool.util.URLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
     * 权限拦截器
     *
     * @author   yajun
     * @create    2019年4月25日
     */
@Component
    public class AuthInterceptor implements HandlerInterceptor {
    //注入springBoot 自动配置好的RedisTemplate
    @Autowired
    private RedisService redisService;
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
                throws Exception {
            //System.out.println(">>>AuthInterceptor>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
            //String  token =   request.getParameter("token");
            String  token  =  request.getHeader("token");
            boolean flag = true;
            String redisToken = null;
            //登陆方法不需要token
            String requestUrl = request.getRequestURI();
            String url = URLUtil.getPath(requestUrl);
            if(url.contains("login")){
                System.out.println("放行");
            }else if(url.contains("register")){
                System.out.println("放行");
            }
            //暂时先关闭token 验证
//            else{
//                redisToken =  redisService.getTokenRedisMath();//查询缓存
//                System.out.println("redisToken:"+redisToken);
//                if (!token.equals(redisToken)){
//                    flag = false;
//                }
//
//            }

            System.out.println("flag:"+flag);
            if(flag) {
                System.out.println("我权限通过");
                return true;// 只有返回true才会继续向下执行，返回false取消当前请求
            }else {
                System.out.println("我被拦截");
                return false; //如果false，停止流程，api被拦截
            }



        }

        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                               ModelAndView modelAndView) throws Exception {
            //System.out.println(">>>AuthInterceptor>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
        }

        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
                throws Exception {
            //System.out.println(">>>AuthInterceptor>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
        }

}
